package com.yc.damai.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.yc.damai.bean.Orderitem;
import com.yc.damai.bean.Orders;
import com.yc.damai.bean.Result;
import com.yc.damai.bean.User;
import com.yc.damai.dao.OrdersDao;

@WebServlet("/order/*")
public class OrderServlet extends BaseServlet{

	private static final long serialVersionUID = 1L;
	
	private OrdersDao odao = new OrdersDao();

	//@Override  重写注解
	/**
	 * The method commit(HttpServletRequest, HttpServletResponse) of type
	 *  OrderServlet must override or implement a supertype method
	 */
	// /order/commit.s
	protected void commit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String addr = request.getParameter("addr");
		// 获取数组型参数
		String[] pid = request.getParameterValues("pid");
		String[] count = request.getParameterValues("count");
		
		User user = (User) request.getSession().getAttribute("loginedUser");
		
		Orders o = new Orders();
		o.setName(name);
		o.setPhone(phone);
		o.setAddr(addr);
		o.setUid(user.getUid());
		
		List<Orderitem> list = new ArrayList<>();
		for (int i = 0; i < count.length; i++) {
			Orderitem oi = new Orderitem();
			oi.setCount(Integer.parseInt(count[i]));
			oi.setPid(Integer.parseInt(pid[i]));
			list.add(oi);
		}
		
		Gson gson = new Gson();
		Result res;
		try {
			odao.addOrders(o, list);
			res = new Result(1, "下单成功");
		} catch (SQLException e) {
			e.printStackTrace();
			res = new Result(0, "下单失败");
		}
		
		response.getWriter().append(gson.toJson(res));
		
		
	}
	
	

}
